<template>
  <div class="line-chart">
    <div class="header" @click.stop>
      <div class="title">
        <div class="title-icon"></div>
        <div class="title-text" v-if="title">{{ title }}</div>
      </div>
      <el-radio-group v-model="selectedStep" size="small" text-color="#CE2827" fill="#ffffff" class="custom-radio-line"
        @change="radioGroupChange" v-if="show">
        <el-radio-button label="月">月</el-radio-button>
        <el-radio-button label="周">周</el-radio-button>
        <el-radio-button label="日">日</el-radio-button>
      </el-radio-group>
    </div>
    <div class="chartTitle">
      <!-- <template v-if="chartTitle.length > 0">
        <div v-for="item, index in chartTitle" :key="index">
          <div class="chartTitle_item">
            <div class="chartTitle_item_Icon" :style="{
              backgroundColor: bgc[index]
            }"></div>
            <div>{{ item }}</div>
          </div>
        </div>
      </template> -->

    </div>
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script>
export default {
  name: 'BiLineChart',
  props: {
    title: {
      type: String,
      default: ''
    },
    chartData: {
      type: Object,
      required: true,
      default: () => ({
        xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        series: [
          {
            name: '销售额',
            type: 'line',
            // smooth: true,
            data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]
          }
        ],
        dateStr: '',
        yAxis: {}
      })
    },
    chartTitle: {
      type: Array,
      default: () => []
    },
    show: {
      type: Boolean,
      default: true
    },
    options: {
      type: Object,
      default: () => ({})
    },
    day: {
      type: String,
      default: "月"
    },
    resize: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      chart: null,
      selectedStep: this.day,
      localChartData: null,
      debounceTimer: null,  // 添加防抖定时器
      chartOptions: {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: this.title === '品牌销售完成金额' ? '12%' : '12%',
          left: '1%',
          right: '4.2%',
          bottom: '3%',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: [0],
            start: this.selectedStep !== '日' ? 0 : 80,
            end: this.selectedStep !== '日' ? 50 : 100,
            minValueSpan: 3,
            maxValueSpan: 5,
            height: 2,
            bottom: 0,
            borderColor: 'transparent',
            backgroundColor: '#e2e2e2',
            fillerColor: 'rgba(167,183,204,0.4)',
            showDetail: false,
            handleStyle: {
              color: '#fff',
              borderColor: '#ACB8D1'
            },
            textStyle: {
              color: '#333'
            },
            zoomOnMouseWheel: true,
            moveOnMouseMove: true,
            moveOnMouseWheel: false,
            preventDefaultMouseMove: true,
            minSpan: 10,
            maxSpan: 100
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            zoomOnMouseWheel: true,
            moveOnMouseMove: true,
            moveOnMouseWheel: false,
            preventDefaultMouseMove: true
          }
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [],
      },
      bgc: ['#EA1111', "#11BD76", '#FDB24D'],
      lastZoomState: { start: 0, end: 100 },
      loading: false,
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val, oldVal) {

        this.loading = false;
        this.updateChart();
        return
        // 清除之前的定时器
        if (this.debounceTimer) {
          clearTimeout(this.debounceTimer);
        }

        // 设置新的防抖定时器
        this.debounceTimer = setTimeout(() => {
          this.$nextTick(() => {
            // 创建数据副本
            let newData = JSON.parse(JSON.stringify(val));
            console.log(newData, '---newDataaaaaaaaaaaaaaaaaaaaaaaaaaaa');
            // 确保有旧数据时才进行合并
            if (this.localChartData && oldVal) {
              // 合并 xAxis 数据
              if (Array.isArray(newData.xAxis) && Array.isArray(this.localChartData.xAxis)) {
                // 根据 dateStr 判断是否需要合并
                if (newData.dateStr !== this.localChartData.dateStr) {
                  newData.xAxis = [...newData.xAxis, ...this.localChartData.xAxis];
                }
              }

              // 合并 series 数据
              if (Array.isArray(newData.series) && Array.isArray(this.localChartData.series)) {
                newData.series = newData.series.map((newSeries, index) => {
                  const oldSeries = this.localChartData.series[index];
                  if (oldSeries && Array.isArray(oldSeries.data) && Array.isArray(newSeries.data)) {
                    // 根据 dateStr 判断是否需要合并
                    if (newData.dateStr !== this.localChartData.dateStr) {
                      return {
                        ...oldSeries,
                        ...newSeries,
                        data: [...newSeries.data, ...oldSeries.data]
                      };
                    }
                  }
                  return newSeries;
                });
              }
              console.log(newData, "22222222222222222222222222222222222")
            }

            // 更新本地数据副本
            this.localChartData = newData;
            if (this.title === '经销库存及出货') {

              console.log(this.localChartData, '---this.localChartData');
            }
            this.loading = false;
            this.updateChart();
          });
        }, 300);
      }
    },
    day(newDay) {
      this.selectedStep = newDay;
    },
    resize:{
      deep: true,
      handler(val){
        console.log(val," :resize=resize")
        this.chart.resize();
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
    window.addEventListener('resize', this.handleResize)

  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.off('click')
      this.chart.dispose()
      this.chart = null
    }
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
    window.removeEventListener('resize', this.handleResize)

    // 移除事件监听器
    document.removeEventListener('fullscreenchange', this.testFullscreenEvent);
    document.removeEventListener('webkitfullscreenchange', this.testFullscreenEvent);
    document.removeEventListener('mozfullscreenchange', this.testFullscreenEvent);
    document.removeEventListener('MSFullscreenChange', this.testFullscreenEvent);
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) {
        console.warn('折线图容器未找到')
        return
      }

      try {
        this.chart = this.$echarts.init(this.$refs.chartRef)
        this.updateChart()
        this.bindEvents()
      } catch (error) {
        console.error('初始化折线图失败:', error)
      }
    },
    updateChart() {
      if (!this.chart) return
      
      const options = {
        ...this.chartOptions,
        xAxis: {
          ...this.chartOptions.xAxis,
          data: this.localChartData ? this.localChartData.xAxis : this.chartData.xAxis
        },
        legend: this.localChartData ? this.localChartData.legend : this.chartData.legend ?? [],
        yAxis: (this.localChartData ? this.localChartData.yAxis : this.chartData.yAxis) ? (this.localChartData ? this.localChartData.yAxis : this.chartData.yAxis).map(item => ({
          ...item,
          type: "value",
          axisLabel: {
            show: true,
            formatter: function (params) {
              let value = params;
              if (value < 1 && value > -1) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${item.unit}`;
              }
              if (value < 10000 && value > -10000) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${item.unit}`;
              }
              else if (value < 100000000 && value > -100000000) {
                const formattedValue = (Math.abs(value) / 10000).toFixed(1);
                return `${value < 0 ? '-' : ''}${formattedValue.replace(/\.0$/, '')}万${item.unit}`;
              }
              else {
                const formattedValue = (Math.abs(value) / 100000000).toFixed(1);
                return `${value < 0 ? '-' : ''}${formattedValue.replace(/\.0$/, '')}亿${item.unit}`;
              }
            }
          },
        })) : {},
        series: (this.localChartData ? this.localChartData?.series  ?? []: this.chartData?.series ?? []).map(item => ({
          ...item,
          label: {
            normal: {
              show: true,
              formatter: function (params) {
                let value = params.data;
                if (value < 1 && value > -1) {
                  return value.toFixed(1).replace(/\.0$/, ''); // 去掉小数点后的0
                }
                else if (value < 10000 && value > -10000) {
                  return ~~value; // 直接取整
                }
                else if (value < 100000000 && value > -100000000) {
                  const formattedValue = (value / 10000).toFixed(1); // 转换为万并保留一位小数
                  return formattedValue.replace(/\.0$/, '')  // 去掉小数点后的0并添加单位
                }
                else {
                  const formattedValue = (value / 100000000).toFixed(1); // 转换为亿并保留一位小数
                  return formattedValue.replace(/\.0$/, '') // 去掉小数点后的0并添加单位
                }
              }
            }
          },
          type: 'line',
          lineStyle: {
            width: 1
          }
        })),
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: [0],
            start: this.selectedStep !== '日' ? this.lastZoomState.start : 80,
            end: this.selectedStep !== '日' ? this.lastZoomState.end : 100,

            // start: 0,
            // end: 50,
            minValueSpan: 3,
            // maxValueSpan: 12,
            height: 3,
            bottom: 0,
            borderColor: 'transparent',
            backgroundColor: '#e2e2e2',
            fillerColor: 'rgba(167,183,204,0.4)',
            showDetail: false,
            handleStyle: {
              color: '#fff',
              borderColor: '#ACB8D1'
            },
            textStyle: {
              color: '#333'
            },
            zoomOnMouseWheel: true,
            moveOnMouseMove: true,
            moveOnMouseWheel: false,
            preventDefaultMouseMove: true,
            minSpan: 10,
            maxSpan: 100
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            zoomOnMouseWheel: true,
            moveOnMouseMove: true,
            moveOnMouseWheel: false,
            preventDefaultMouseMove: true
          }
        ]
      }
      let listener = function () {
        if (this.chart) {
          this.chart.resize();
        }
      };
      this.chart.setOption(options, true);
      // EleResize.on(this.$refs.chartContainer, listener);
      // 监听 dataZoom 事件
      this.chart.off('dataZoom');
      this.chart.on('dataZoom', (event) => {
        const currentStart =  event?.start ?? event.batch[0].start ;
        const currentEnd =   event?.end ?? event?.batch[0].end ;
        this.lastZoomState = { start: currentStart, end: currentEnd };
        console.log(currentStart, '---currentStart');
        console.log(currentEnd, '---currentEnd');
        if (currentEnd - currentStart >= 80) {
          if (this.chartData.dateStr) {
            this.loading = true;
            this.$emit('dataZoom', { data: this.chartData.dateStr, title: this.title, day: this.selectedStep });
          }
        }
      });
      
    },
    bindEvents() {
      if (!this.chart) return

      // 移除之前的点击事件
      this.chart.off('click')

      // 只在图表区域添加点击事件
      this.chart.getZr().on('click', (params) => {
        // 检查点击是否在图表区域内
        const pointInGrid = this.chart.containPixel({ gridIndex: 0 }, [params.offsetX, params.offsetY])
        if (pointInGrid) {
          this.$emit('chart-click', params)
        }
      })
    },
    handleResize() {
      this.chart && this.chart.resize()
    },
    radioGroupChange() {
      console.log(this.selectedStep, '---this.selectedStep');
      // 重置本地图表数据
      this.localChartData = null;
      // 重置缩放状态
      this.lastZoomState = { start: 0, end: 100 };
      // 触发加载状态
      this.loading = true;

      // 完全重新初始化图表
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
        this.$nextTick(() => {
          console.log('数据格式化');
          this.initChart();
        });
      }
      this.$emit('update:day', this.selectedStep);
      this.$emit("Change", {
        title: this.title,
        selectedStep: this.selectedStep
      })
    },
    reset() {
      this.selectedStep = "月"
    },
    resetChart() {
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
        this.$nextTick(() => {
          console.log('数据格式化');
          this.initChart();
        });
      }
    },
    toggleFullscreen() {
      console.log('手动触发全屏');
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().catch(err => {
          console.error('进入全屏失败:', err);
        });
      } else {
        document.exitFullscreen();
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.line-chart {
  width: 100%;
  height: 100%;
  padding: 0 10px;

  .title {
    display: flex;
    align-items: center;
  }

  .title-text {
    font-weight: 500;
    font-size: 20px;
    color: #333333;
    margin: 0 0 0 6px;
  }

  .title-icon {
    width: 20px;
    height: 20px;
    background-color: #000;
    border-radius: 50%;
    background: url('../../../assets/BI/icon.png') no-repeat center center;
    background-size: 100% 100%;
  }

  .chartTitle {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    column-gap: 20px;
    font-size: 14px;
    color: #666666;

    &_item {
      display: flex;
      align-items: center;
      column-gap: 6px;

      &_Icon {
        width: 16px;
        height: 8px;
        border-radius: 6px;
      }
    }
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 45px;
  }

  h3 {
    font-size: 16px;
  }

  .chart {
    height: calc(100% - 60px);
    // height: 246px;
    cursor: pointer;
    position: relative;
    z-index: 1;
  }
}
</style>